Hello everyone,
I'm new to android. Recently I learn how to create Tabwidget. This function is useful. But I find that I cannot add the widgets I want in R.layout.xxxx. So I try to do it by java code. But unfortunately it failed.
By using XML, I do the following. The program works without problem.
public class ShowBalanceActivity extends Activity implements AdapterView.OnItemSelectedListener
{
private Spinner monthview;
private ArrayAdapter monthadapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.balance);
monthadapter = ArrayAdapter.createFromResource(
this, R.array.months, android.R.layout.simple_spinner_item);
monthadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
monthview = (Spinner) findViewById(R.id.monthlist);
monthview.setOnItemSelectedListener(this);
monthview.setAdapter(monthadapter);
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
}
For the Java code part, I use the following,
public class BalanceLayout extends TabActivity implements TabHost.TabContentFactory
{
private Activity activity;
private LayoutInflater inflaterHelper = null;
private Spinner monthview = null;
private LinearLayout layout;
private static final String Tab1 = "By Date";
private static final String Tab2 = "By Categories";
private ArrayAdapter <String> monthadapter = null;
public BalanceLayout (Activity a)
{
activity = a;
inflaterHelper = a.getLayoutInflater();
}
public View addCustomView(String id)
{
layout = new LinearLayout(activity);
layout.setOrientation(LinearLayout.VERTICAL);
if(id.equals(Tab1))
{
Spinner monthview = new Spinner(activity);
ArrayAdapter <String> monthadapter = new ArrayAdapter <String> (this,
android.R.layout.simple_dropdown_item_1line, MONTHS);
monthadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
monthview.setAdapter(monthadapter);
monthview.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
layout.addView(monthview,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
else if(id.equals(Tab2))
{
}
return layout;
}
}
But it causes force close when I execute the program. It seems that I cannot use findViewById method to create the view like XML.
I read many documentations and search android docs and internet. I cannot find the solution. Hope that some of you know what happened to my code and solution to solve
Thanks !!
Tom