I have tried to add rating bar in Linear Layout at dynamically after some textfields. But I'm getting NullPointerException at the line = lL.addView(rating); Can someone help me please how to do this.Thanks in Advance.
Here is my xml file.
<ScrollView
android:id="#+id/scrollField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btnDELETE"
android:layout_below="#+id/textTitle"
android:layout_marginTop="10dp" >
<LinearLayout
android:id="#+id/linearLayoutRatingDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_EmployeeName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskDate"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskRate"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
</LinearLayout>
</ScrollView>
Hare is my Activity code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.task_details);
Intent intent = getIntent();
str_IntentName = intent.getExtras().getString("EMP_NAME");
str_IntentTaskName = intent.getExtras().getString("TASK_NAME");
str_IntentDate = intent.getExtras().getString("TASK_DATE");
str_IntentRate = intent.getExtras().getString("TASK_RATE");
numStar = Integer.valueOf(str_IntentRate);
Log.e("integer numStar "," = " + numStar);
lL = (LinearLayout)findViewById(R.id.linearLayoutRatingDetails);
tvEmpName.setText(str_IntentName);
tvTaskName.setText(str_IntentTaskName);
tvDate.setText(str_IntentDate);
tvRate.setText(str_IntentRate);
Create_RatingBar();
}
private void Create_RatingBar()
{
stepSize = (float) 0.5;
rating = new RatingBar(Task_Details.this);
rating.setNumStars(numStar);
rating.setStepSize(stepSize);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
param.topMargin = 500;
rating.setLayoutParams(param);
lL.addView(rating);
}
In order to add it to the LinearLayout from your xml you need to get a "reference" to this LinearLayout in your code. For that you need to ad id it in xml and get an element using this id in your code.
public void onCreate(Bundle savedInstanceState){
//Some other code for other views
ViewGroup container = (ViewGroup) findViewById(R.id.linearLayoutRatingDetails);
setupRatingBar(container)
}
private void setupRatingBar(ViewGroup ratingBarContainer){
RatingBar ratingBar = new RatingBar(Task_Details.this);
//All methods you need to initialize the rating bar
//including setNumStars(), setStepSize() and layout params
ratingBarContainer.addView(ratingBar);
}
Also use more explanatory names. "lL" will cause you headache in the future.
Related
I wish to add a custom tailored layout for each ListView item. I have an empty linear layout in the xml layout file for ListView item layout. It has horizontal orientation.
I wish to add three FrameLayouts dynamically to above mentioned LinearLayout and set custom weight for each FrameLayout.
I found a part of the solution for it, as in the code below. Problem arises when the ListView has to be updated. ListView is initially hidden. When a certain button is pressed, ListView gets updated (hash map cleared and then filled with a new data set) and its visibility set from GONE to VISIBLE. Next thing is to loop through all the items and add designed view programmatically.
If I invoke the method add_designed_views(null); right after updating ListView items, the app loops through items, creates all the new views and adds them to right items. However, they are not added. I know this because of check if the item is already added, and if I invoke this method several times in a row, it will do the same each time, as if it didn't add anything at all.
Next thing that I tried is I postponed adding views dynamically by invoking the method add_designed_views from onClick of a dummy button. When I see the list has loaded (without the custom views) I press the dummy button and the custom views appear. But every 6th is missing. If I press it again, the missing ones appear. Which makes me even more confused.
It's obvious that the views can't be added immediately after changing the visibility of ListView. Probably because it takes the system some time to inflate the ListView, or it does some background task, but I couldn't find any listener or some function that tells me that it has finished loading so that I can add my views then.
Custom ListView item layout (xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="110dp"
android:background="#drawable/textview_border_dark_line"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="21"
android:minHeight="40dp">
<TextView
android:id="#+id/text1"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="15dp"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="70"
android:minHeight="90dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/path_model"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:orientation="horizontal"
android:onClick="onClick_listItem"
>
<!-- Path Model. -->
<!-- This is where I add view dynamically. -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:orientation="vertical">
<TextView
android:id="#+id/text2"
android:textSize="12dp"
android:textColor="#454545"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="50"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="10">
<ImageView
android:id="#+id/ic_time"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/clock"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/text4_1"
android:textSize="14dp"
android:textColor="#454545"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="50"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/ic_time" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="10">
<ImageView
android:id="#+id/ic_changes"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/change"
android:layout_centerVertical="true"/>
<TextView
android:id="#+id/text4_2"
android:textSize="14dp"
android:textColor="#454545"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="50"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/ic_changes"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="10">
<ImageView
android:id="#+id/ic_cost"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/coins"
android:layout_centerVertical="true"/>
<TextView
android:id="#+id/text4_3"
android:textSize="14dp"
android:textColor="#454545"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="50"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/ic_cost"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="10">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="21"
android:minHeight="38dp">
<TextView
android:id="#+id/text3"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="15dp"
/>
</RelativeLayout>
</LinearLayout>
add_designed_views method (Java):
public void add_designed_views(View view)
{
for(int i=0; i<hashmap_search_results_list.size(); i++)
{
/* Check if it is already added. We have to check,
because we run it twice in consecutive order. */
LinearLayout listView_item = (LinearLayout)getViewByPosition(i, listView_search_results);
View middle_ground = ((ViewGroup) listView_item).getChildAt(1);
LinearLayout path_model = (LinearLayout) ((ViewGroup) middle_ground).getChildAt(0);
LinearLayout already_added_ll_path = (LinearLayout)((ViewGroup)path_model).getChildAt(0);
if(already_added_ll_path != null)
{
Log.d(TAG, "Already has linear layout: " + hashmap_search_results_list.get(i).get("latest_departure_time"));
continue;
}
Log.d(TAG, "Doing: " + hashmap_search_results_list.get(i).get("latest_departure_time"));
Search_Result_Item result_item = (Search_Result_Item)search_results_list.get(i);
/* How to access each view at each item position in list view. */
//LinearLayout listView_item = (LinearLayout) getViewByPosition(i, listView_search_results);
//View middle_ground = ((ViewGroup) listView_item).getChildAt(1);
//LinearLayout path_model = (LinearLayout) ((ViewGroup) middle_ground).getChildAt(0);
/* Setting the proportions of lines regarding walking time and riding time. */
HrMin hrmin_walking_to_entrance_time = result_item.walking_to_entrance_time();
HrMin hrmin_riding_time = result_item.travel_time();
HrMin hrmin_walking_from_exit_time = result_item.walking_from_exit_time();
int int_walking_to_entrance_time = hrmin_get_minutes(hrmin_walking_to_entrance_time);
int int_riding_time = hrmin_get_minutes(hrmin_riding_time);
int int_walking_from_exit_time = hrmin_get_minutes(hrmin_walking_from_exit_time);
int total = int_walking_to_entrance_time +
int_riding_time +
int_walking_from_exit_time;
float weight_walking_to_entrance = (float)int_walking_to_entrance_time/total;
float weight_bus_ride = (float)int_riding_time/total;
float weight_walking_from_exit = (float)int_walking_from_exit_time/total;
/* How to add a new layout, view to existing layout. */
LinearLayout ll_path = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
/* Pedestrian image. */
ImageView pedestrian = new ImageView(this);
pedestrian.setBackground(getResources().getDrawable(R.drawable.runner_rnd));
int dimensionInPixel = 16;
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams pedestrian_params = new FrameLayout.LayoutParams(
dimensionInDp,
dimensionInDp,
Gravity.CENTER_VERTICAL);
pedestrian.setLayoutParams(pedestrian_params);
/* Gray Line. */
FrameLayout frameLayout_pedestrian_container = new FrameLayout(this);
LinearLayout.LayoutParams frame_layout_params = new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.MATCH_PARENT,
weight_walking_to_entrance);
View gray_line = new View(this);
gray_line.setBackground(getResources().getDrawable(R.drawable.horizontal_gray_line));
dimensionInPixel = 4;
dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams gray_line_params = new FrameLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dimensionInDp,
Gravity.CENTER_VERTICAL);
gray_line.setLayoutParams(gray_line_params);
frameLayout_pedestrian_container.addView(gray_line);
frameLayout_pedestrian_container.addView(pedestrian);
frameLayout_pedestrian_container.setLayoutParams(frame_layout_params);
ll_path.addView(frameLayout_pedestrian_container);
/* Bus image. */
FrameLayout frameLayout_bus_container = new FrameLayout(this);
LinearLayout.LayoutParams frame_layout_bus_params = new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.MATCH_PARENT,
weight_bus_ride);
ImageView bus = new ImageView(this);
bus.setBackground(getResources().getDrawable(R.drawable.bus_rnd));
dimensionInPixel = 17;
dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams bus_params = new FrameLayout.LayoutParams(
dimensionInDp,
dimensionInDp,
Gravity.CENTER_VERTICAL);
bus.setLayoutParams(bus_params);
/* Green line. */
View green_line = new View(this);
green_line.setBackground(getResources().getDrawable(R.drawable.horizontal_green_line));
dimensionInPixel = 4;
dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams green_line_params = new FrameLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dimensionInDp,
Gravity.CENTER_VERTICAL);
green_line.setLayoutParams(green_line_params);
frameLayout_bus_container.addView(green_line);
frameLayout_bus_container.addView(bus);
frameLayout_bus_container.setLayoutParams(frame_layout_bus_params);
ll_path.addView(frameLayout_bus_container);
/* Walking from exit path. */
ImageView pedestrian2 = new ImageView(this);
pedestrian2.setBackground(getResources().getDrawable(R.drawable.runner_rnd));
dimensionInPixel = 16;
dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams pedestrian_params2 = new FrameLayout.LayoutParams(
dimensionInDp,
dimensionInDp,
Gravity.CENTER_VERTICAL);
pedestrian2.setLayoutParams(pedestrian_params2);
/* Gray Line. */
FrameLayout frameLayout_pedestrian_container2 = new FrameLayout(this);
LinearLayout.LayoutParams frame_layout_params2 = new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.MATCH_PARENT,
weight_walking_from_exit);
View gray_line2 = new View(this);
gray_line2.setBackground(getResources().getDrawable(R.drawable.horizontal_gray_line));
dimensionInPixel = 4;
dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
FrameLayout.LayoutParams gray_line_params2 = new FrameLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
dimensionInDp,
Gravity.CENTER_VERTICAL);
gray_line2.setLayoutParams(gray_line_params2);
frameLayout_pedestrian_container2.addView(gray_line2);
frameLayout_pedestrian_container2.addView(pedestrian2);
frameLayout_pedestrian_container2.setLayoutParams(frame_layout_params2);
ll_path.addView(frameLayout_pedestrian_container2);
ll_path.setLayoutParams(params);
ll_path.setOrientation(LinearLayout.HORIZONTAL);
path_model.addView(ll_path);
}
}
Part where I update the ListView and show it:
search_results.setVisibility(View.VISIBLE);
ListView is a child of two layouts:
<LinearLayout
android:id="#+id/search_results"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:visibility="gone"
android:paddingTop="140dp"
android:orientation="vertical"
android:onClick="onClick_nothing">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/search_options_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="#+id/mapView"
app:layout_constraintTop_toTopOf="#+id/mapView"
android:background="#android:color/white"
android:orientation="vertical"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarThumbVertical="#android:color/darker_gray"
/>
</RelativeLayout>
</LinearLayout>
One thing that helped is Handler.postDelayed():
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
add_designed_views (null);
}
}, 300);
This function delays method call for 300 mS. Programmatically added layouts are visible. But, still every 6th is missing. They also appear after I touch any of the items.
I have EditViews to prompt the user for a min and max. The data entered is passed into an Activity function and a random number is generated. That random number is passed onto another Activity to be displayed. When I enter a min number and a max number and then click the button that says generate, I get directed to a blank screen. However, I'm expecting randValue to be displayed.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public final static String RAND_NUM = "com.example.random.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void generateNum(View view) {
Intent intent = new Intent(this, DisplayNumActivity.class);
EditText minInput = (EditText) findViewById(R.id.min_num);
EditText maxInput = (EditText) findViewById(R.id.max_num);
int minNum = Integer.parseInt(minInput.getText().toString());
int maxNum = Integer.parseInt(maxInput.getText().toString());
Random rand = new Random();
int randNum = rand.nextInt(maxNum - minNum) + minNum;
intent.putExtra(RAND_NUM, randNum);
startActivity(intent);
}
}
DisplayNumActivity.java
public class DisplayNumActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_num);
Intent intent = getIntent();
String randValue = intent.getStringExtra(MainActivity.RAND_NUM);
TextView textView = new TextView(this);
textView.setTextSize(30);
textView.setText(randValue);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_num);
layout.addView(textView);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.example.random.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Min number"
android:id="#+id/textView"
android:layout_marginTop="40dp"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/textView2"
android:layout_alignStart="#+id/textView2" />
<EditText
android:id="#+id/min_num"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="min"
android:inputType="number"
android:layout_marginTop="32dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Max number"
android:id="#+id/textView2"
android:layout_marginTop="43dp"
android:layout_below="#+id/min_num"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/max_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="max"
android:inputType="number"
android:minWidth="500dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_text"
android:onClick="generateNum"
android:id="#+id/button"
android:layout_below="#+id/max_num"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp" />
OK, two things:
1) In DisplayNumActivity, change
String randValue = intent.getStringExtra(MainActivity.RAND_NUM);
to this:
int randValue = intent.getIntExtra(MainActivity.RAND_NUM, 0);
Here we are reading in an int value from the intent instead of a String. In your main activity you saved an int here, not a String, the String here is just the "key" in the key-value pair. The zero is just a default in case it can't find your int.
2) To display the number you have to first change that int back to a String in order to set it in a TextView and then we display it to your relative layout like this:
String stringRandValue = Integer.toString(randValue);
View relativeLayout = findViewById(R.id.activity_display_num);;
TextView textView = new TextView(this);
textView.setTextSize(30);
textView.setText(stringRandValue);
((RelativeLayout)relativeLayout).addView(textView);
That should work.
Replace this
String randValue = intent.getStringExtra(MainActivity.RAND_NUM);
With this
String randValue = intent.getIntExtra(MainActivity.RAND_NUM,
default_int_value);
I think you have to specify exactly which layout you want to add your textview to.
Like: RelativeLayout relativelayout = (RelativeLayout)findViewById(R.id.relativelayoutID);
Casting to viewgroup seems bit heavy to me. Please try suggested way and let me know if it changes anything for you.
Edit: There is one more thing which I feel might be the culprit in this case and that is missing layout params for your text View.
Example:
//create params like this
LayoutParams layoutparams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
//set layout params like this
textView.setLayoutParams(layoutparams);
Note - replace the parent layout type according to your xml where this textView is been added.
I'm a newbie.
I want to add 3 EditText's when a user click on a button.
I try to realize it, but it isn't work.
Widgets do not appear.
P.S. Widgets must be in others layout's.
Thank you for help.
Sorry for my bad English.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg_fill"
android:id="#+id/simple_main_layout">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/for_main_text">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="60dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Buy List"
android:id="#+id/textView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="67dp"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/do_new_list"
android:layout_marginLeft="153dp"
android:layout_marginRight="2dp"
android:background="#drawable/btn_yes" android:textColor="#804f29" android:textStyle="bold"/>/>
</LinearLayout>
<EditText
android:layout_width="305dp"
android:layout_height="wrap_content"
android:id="#+id/editText" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="91dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText3" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Code:
private Button do_new_field;
private EditText[] text, many, cost;
private final int fields = 50;
private int last_field = 0;
private LinearLayout layoutik;
LinearLayout.LayoutParams layoutParams;
LinearLayout.LayoutParams layoutParams2;
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_buy);
do_new_field = (Button) findViewById(R.id.do_new_list);
layoutik = (LinearLayout) findViewById(R.id.for_main_text);
do_new_field.setOnClickListener(this);
text = new EditText[fields];
many = new EditText[fields];
cost = new EditText[fields];
layoutParams =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT,0f);
layoutParams2 =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT,0f);
}
#Override
public void onClick(View view) {
if(view == do_new_field)
{
if(last_field <= fields)
{
text[last_field] = new EditText(this);
many[last_field] = new EditText(this);
cost[last_field] = new EditText(this);
text[last_field].setWidth(305);
text[last_field].setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
text[last_field].setMaxLines(3);
many[last_field].setWidth(91);
many[last_field].setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
many[last_field].setInputType(InputType.TYPE_CLASS_NUMBER);
many[last_field].setMaxLines(1);
cost[last_field].setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
cost[last_field].setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
cost[last_field].setInputType(InputType.TYPE_CLASS_NUMBER);
cost[last_field].setMaxLines(1);
text[last_field].setId(100 + last_field);
many[last_field].setId(200 + last_field);
cost[last_field].setId(300 + last_field);
text[last_field].setLayoutParams(layoutParams);
many[last_field].setLayoutParams(layoutParams);
cost[last_field].setLayoutParams(layoutParams);
layoutik.addView(text[last_field]);
layoutik.addView(many[last_field]);
layoutik.addView(cost[last_field]);
last_field++;
}
}
}
}
You might have to add "setId" to the editText and check.
TableLayout.LayoutParams params = new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 0f);
editText.setId(EDT_ID + sub_count + i);
editText.setTag(insertAdAl.get(i).getmApiAppend());
editText.setLayoutParams(params);
editText.setTextAppearance(NewAdverts.this,
android.R.style.TextAppearance_Small);
editText.setGravity(Gravity.LEFT | Gravity.CENTER);
editText.setPadding(4, 4, 4, 4);
editText.setTextAppearance(NewAdverts.this,
android.R.attr.textAppearanceSmall);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(R.drawable.notification_field);
Making a simple program which will generate a multiple choice form. I have an sing_select.xml which acts as the template for making each question. Then, in code I wanted to populate my main.xml with a bunch of these templates customized. Though it works great for the first question, any subsequent questions do not get displayed. Not sure what I'm doing wrong. I know there isn't an overlap as I manually hid the first question.
Java File
public class FormFillerActivity extends Activity
{
private LinearLayout mQuestionList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Must come before setContentView or program crashes
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Must set before accessing layout elements or program crashes
setContentView(R.layout.main);
mQuestionList = (LinearLayout) findViewById(R.id.Body_Layout);
initForm();
}
private void initForm()
{
int count = 1;
ArrayList<String> answers = new ArrayList<String>();
answers.add("Single");
answers.add("Married");
answers.add("Separated");
answers.add("Divorced");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your marital status?", answers));
answers.clear();
answers.add("Male");
answers.add("Female");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your gender?", answers));
}
private View addSingSelectQuestion(int count, String question, ArrayList<String> answers)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View container = inflater.inflate(R.layout.sing_select, null);
((TextView) container.findViewById(R.id.Sing_Select_Num)).setText(count + ") ");
((TextView) container.findViewById(R.id.Sing_Select_Text)).setText(question);
RadioGroup rg = (RadioGroup) container.findViewById(R.id.Sing_Select_Answer);
//Generate radio group answers
Iterator<String> it = answers.iterator();
while (it.hasNext())
{
RadioButton rb = new RadioButton(rg.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
String ans = it.next();
rb.setId(answers.indexOf(ans));
rb.setLayoutParams(params);
rb.setText(ans);
rb.setTextColor(getResources().getColor(R.color.black));
rb.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_normal));
rg.addView(rb);
}
return container;
}
}
main.xml (stripped out unrelated UI elements)
<?xml version="1.0" encoding="utf-8"?>
...
<ScrollView
android:id="#+id/Body_Scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/Footer"
android:layout_below="#id/Title"
android:scrollbars="vertical" >
<LinearLayout
android:id="#+id/Body_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/marg_normal"
android:padding="#dimen/pad_large" >
</LinearLayout>
</ScrollView>
...
sing_select.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Sing_Select_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:padding="8dp" >
<TextView
android:id="#+id/Sing_Select_Num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#) "
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<TextView
android:id="#+id/Sing_Select_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Sing_Select_Num"
android:layout_toRightOf="#+id/Sing_Select_Num"
android:text="The Question?"
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<RadioGroup
android:id="#+id/Sing_Select_Answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Sing_Select_Text"
android:layout_below="#+id/Sing_Select_Text"
android:layout_toLeftOf="#+id/Sing_Select_Trans_Button" >
</RadioGroup>
<Button
android:id="#+id/Sing_Select_Trans_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_big"
android:padding="8dp"
android:text="Accept"
android:textSize="#dimen/txt_button" />
</RelativeLayout>
Try to set orientation to vertical for the *Body_Layout* LinearLayout. I think your pushing out of the screen the next rows after the first one(the width for the inflated view is set to fill the parent).
Good day everyone,
I'm learning Android development and I try to build some dynamic lists for my application. And I'm stuck... like for 4 hours already.
I have two layouts:
1. main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/action_buttons"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:gravity="center"
>
<Button
android:id="#+id/button_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_calculate" />
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/button_count"
android:text="#string/button_add" />
</LinearLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/action_buttons"
>
<LinearLayout
android:id="#+id/action_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
action_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/action_list_item_root"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/action_list_item_edittext_drinkName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/action_list_item_button_remove"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/action_list_item_title"
android:padding="10dp" />
<EditText
android:id="#+id/action_list_item_edittext_drinkPercent"
android:text="40"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/action_list_item_edittext_drinkAmount"
android:inputType="number"
android:padding="10dp"/>
<EditText
android:id="#+id/action_list_item_edittext_drinkAmount"
android:text="0.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/action_list_item_button_remove"
android:layout_alignBottom="#+id/action_list_item_button_remove"
android:inputType="numberDecimal"
android:width="50dp"
android:padding="10dp" />
<Button
android:id="#+id/action_list_item_button_remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="#string/action_list_item_button_remove" />
And code that creates dynamic list:
public class MainActivity extends Activity {
LinearLayout actionList = null;
private Button btnAdd;
private Button btnCalculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initActivityElements();
}
private void initActivityElements() {
initAddButton();
initCalculateButton();
}
private void initCalculateButton() {
btnCalculate = (Button) findViewById(R.id.button_count);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView amount = (TextView) findViewById(R.id.action_list_item_edittext_drinkAmount);
//this retrives TextView value from first list
Toast.makeText(getApplicationContext(), amount.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
});
}
private void initAddButton() {
actionList = (LinearLayout) findViewById(R.id.action_list);
btnAdd = (Button) findViewById(R.id.button_add);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout listItem = (RelativeLayout) View.inflate(
MainActivity.this, R.layout.action_list_item, null);
TextView name = (TextView) listItem
.findViewById(R.id.action_list_item_edittext_drinkName);
name.setText("Here is the Title " + actionList.getChildCount());
listItem.findViewById(R.id.action_list_item_button_remove)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
actionList.removeView((View) v.getParent());
}
});
actionList.addView(listItem);
}
});
}
My problem is that I need to get all data from TextView boxes (Amount, Percent), but I can retrive that data only from first item of a list (look at onClickListener for btnCalculate) and can't figure out how to do it, but tried to add 'unique ids' for view (but that brakes layout, badly), tried setting Tags but again with no luck.
Maybe anyone can give a tip? I bet there is some easy way to do it, but I'm failing to find it and google is no help here.
Thanks
I'm not really sure what exactly you are trying to do but it sounds like you are trying to take in information and populate it into a view. I would recommend having a static text box that takes in your information and builds that into a listview. A good example of how to do that is located here http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html.