ページ 11

Androidアプリのエラーについて(seContentView)

Posted: 2013年2月07日(木) 19:52
by はち
AndroidアプリsetContentViewのエラーについて

ただ今Androidのアプリを作成しているのですが、
起動時にエラーが出てしまい起動する事すら出来ません。
どうやら原因が
setContentViewとfindViewIdにあるみたいなのですが
どうしてダメなのかが分かりません。

ソースコードはこちらです。

コード:

package wall.size;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.app.WallpaperManager;
import android.content.Intent;
import android.widget.TextView;

public class MainActivity extends TabActivity {
private EditText et1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


//タブの定義

TabHost tabHost = getTabHost();
LayoutInflater inflater = getLayoutInflater();
inflater.inflate(R.layout.tab1, tabHost.getTabContentView(), true);
inflater.inflate(R.layout.tab2, tabHost.getTabContentView(), true);
TabSpec tab1 = tabHost.newTabSpec("tab1");
tab1.setIndicator("サイズ");
tab1.setContent(R.id.sample1);
TabSpec tab2 = tabHost.newTabSpec("tab2");
tab2.setIndicator("検索");
tab2.setContent(R.id.sample2);
tabHost.addTab(tab1);
tabHost.addTab(tab2);

//検索ボックス
final EditText keyword;

keyword = (EditText)findViewById(R.id.et1);
Button button = (Button)findViewById(R.id.button1);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("KEYWORD", keyword.getText().toString());
startActivityForResult(intent, 0);
}
});

//画面サイズの抽出

setContentView(R.layout.tab2);
this.et1 = ((EditText) findViewById(R.id.et1));
WallpaperManager wm = WallpaperManager.getInstance(this);

TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
int width = wm.getDesiredMinimumWidth();
int height = wm.getDesiredMinimumHeight();
text1.setText("壁紙の幅:" + String.valueOf(width) + "px");
text2.setText("壁紙の高さ:" + String.valueOf(height) + "px");

}
}

詳しい方いらっしゃいましたら、お願いいたします。

Re: Androidアプリのエラーについて(seContentView)

Posted: 2013年2月08日(金) 00:02
by ISLe
R.id.et1とかR.id.button1は、R.layout.tab1かR.layout.tab2のレイアウトに含まれているのでしょうか。
そうであれば、ActivityのfindViewByIdを使うのではなくて、LayoutInflater#inflateが返すViewを覚えておいて、そのViewのfindViewByIdを使う必要があります。

あと、
setContentView(R.layout.tab2);
だとR.layout.tab2で新しくViewが作られてしまうのでは?
というかTabActivityにsetContentViewは不要かと。

xml上のレイアウトだけではなく、作成されたViewインスタンスの階層をきちんと把握しましょう。