这是MainActivity
//class declare
public class MainActivity extends Activity {
// a lot of code
}
//OnCreate Set
setContentView(R.layout.activity_main);
和Inside里面有一个ID为R.id.widget101
的TableLayout,TableLayout有一个动态创建的LinearLayout。
这是第二个活动代码,试图获取MainActivity TableLayout并获取所有内部LinearLayout子项
//class declare
public class SecondActivity extends Activity {
// a lot of code
}
//OnCreate Set
setContentView(R.layout.second);
public void EnableButton(boolean bool){
View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_main, null);
ViewGroup layout = (ViewGroup) view.findViewById(R.id.widget101);
if (layout != null){
Log.d(null,"EnableButton getchild="+layout.getChildCount()+"");
Log.d(null,"EnableButton Function");
}
}
问题在这里发生,当调用MainActivity以获取TableLayout Child的第二个Aciticity返回0
=============================================== ================
这就是我如何调用SecondActivity
public class MainActivity extends Activity
implements OnClickListener {
//overrides the OnClickListener interface method
@Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.btnWEmas){
//define a new Intent for the second Activity
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("From_LocationName",global.From_LocationName);
intent.putExtra("To_LocationName",global.To_LocationName);
TextView textview = (TextView) findViewById(R.id.lblPrice);
intent.putExtra("Price",textview.getText());
//start the second Activity
this.startActivity(intent);
}
// still have a lot of code
答案 0 :(得分:0)
将此放在您的第一个活动中
static ViewGroup layout ; //define it globally
layout = (ViewGroup) view.findViewById(R.id.widget101); //put it inside the oncreate of main activity
并将此对象用于第二个活动
public void EnableButton(boolean bool){
View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_main, null);
if (MainActivity.layout != null){
Log.d(null,"EnableButton getchild="+MainActivity.layout.getChildCount()+"");
Log.d(null,"EnableButton Function");
}
}
答案 1 :(得分:0)
您应该遵循以下方案:
创建一个Custom类文件,其中包含Table布局及其子元素。使用context参数创建默认构造函数。请点击以下链接以获得更清晰的信息。
https://stackoverflow.com/a/20367698/1944782
在这里,我创建了一个自定义Toast,您可以根据它自定义表格布局。
还有一件事,请尽可能忽略静态变量的使用。它会导致内存泄漏并导致应用程序崩溃。