开发者

How to load linearlayout dynamically after checking a condition in the class file?

Hey guys please help me out I am new to android application development

Here is the scenerio: This is my layout declaring xml file:

<LinearLayout xxx
         <Textview aaa>
          </TextView>
</LinearLayout>

//The below LinearLayout I need to display when it meets some condition in java class i.e if(true) then display the following layout else dont. I can check this condition only after user provides some input.

<LinearLayout xxx
         <Textview aaa>
                To be displayed after the condition is checked
          </TextView>
</LinearLay开发者_如何学JAVAout>

//following layout is displayed with the first one.

<LinearLayout xxx
         <Textview aaa>
          </TextView>
</LinearLayout>

Any idea how to do it?


Take a few moments to read the android dev guide. It is worth the time: http://developer.android.com/guide/topics/ui/index.html

Basically, you want to use IDs to refer to the xml layout:

android:id="@+id/myxmlid"

and in your java file:

LinearLayout ll = findViewById(R.id.myxmlid);
if (yourCondition)
  mainLayout.add(ll);

I'm assuming that you want to add a widgets to the current layout, rather than just change the text of the current TextView.

Also, this assumes that you want to add more than just a new TextView. If you only need that, you don't need to wrap it in a LinearLayout, which is used to add rows or columns of widgets.


You don't replace your entire layout programmatically just to change the text in one TextView. The way this kind of thing is handled in android, is to include a field in your Activity class for your textview, then instantiate it in your onCreate() method with findViewById() after you've called setContentView() to load the layout so that you can access that TextView's fields and methods.

First, you TextView needs an id in the layout xml.

<TextView android:id="@+id/sometext" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />

Then in your Activity...

TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   mTextView = (TextView) findViewById(R.id.sometext);
}

Somewhere else in the program...

public void myMethod(){

   mTextView.setText("Text says this now");

}

Hopefully that gets the idea across. Good luck!


Thank Aleadam for suggesting me to read the link. Follwoing was my approach to get the output.

What I did was I assigned my LinearLayout Visibility to "GONE" (android:Visibility="GONE") when declarning the XML, and in the program after the condition is met, changed the visibility to "VISIBLE". (by using layout.setVisibility(View.VISIBLE))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜