爲了在運行時動態顯示加載視圖,我創建了一個self_pro_bar.xml並創建了一個普通的java類ShyProgressBar。將自定義視圖添加到代碼的主視圖中,然後,如果在Activity類中調用findViewById,它可以找到添加的自定義視圖,但它會從普通Java類調用findViewById,它總是返回null。在Activity之外調用findViewById返回null
self_pro_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/selfprogressbar"
android:gravity="center_horizontal"
android:layout_marginTop="20dp"
android:layout_width="100dp"
android:layout_height="30dp"
android:orientation="horizontal"
android:background="#eee">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="loading..."
/>
</LinearLayout>
ShyProgressBar類
public class ShyProgressBar {
private Context context;
public ShyProgressBar(Context context) {
this.context = context;
}
public View get() {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.self_pro_bar, null);
}
public boolean exist(Activity activity) {
return activity.findViewById(R.layout.self_pro_bar) != null;
}
}
主要業務XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="load_data"
android:text="@string/click_me" />
<LinearLayout
android:id="@+id/dataview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
主要活動
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void load_data(View v) {
ShyProgressBar ins = new ShyProgressBar(this);
View p_b = ins.get();
if(!ins.exist(MainActivity.this)) {
LinearLayout rl = (LinearLayout) findViewById(R.id.dataview);
rl.addView(p_b);
Object c = ins.exist(MainActivity.this) // this code still returns null!
}
}
}
- 不工作 - 在ShyProgressBar中調用findViewById時,對象c值仍然爲空。
- 如果使用below語句判斷視圖是否存在於Activity類的load_data方法中, 查看p_b_v = findViewById(R.id.selfprogressbar);它工作正常,值不爲空。
不確定爲什麼findViewById在活動中工作,但不適用於非活動類。
爲什麼有人會提出我的問題?我怎麼知道誰投入了?我對此很生氣! – user2574853 2014-09-30 12:19:50
你不知道布羅冷靜下來:) – 2014-09-30 12:22:30
@BatuhanC,這是一個不用任何理由獻身的好行爲...感謝您的意見。 – user2574853 2014-09-30 12:23:27