Unable to set TextView programatically - java

I want to show a list of three separate textviews in my linear layout. I'm aware that this can be done from the XML file itself , but I want to generate these textviews dynamically.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id = "#+id/ll1">
</LinearLayout>
Java file:
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RegistrationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle saved){
LinearLayout ll = findViewById(R.id.ll1);
super.onCreate(saved);
setContentView(R.layout.activity_reg);
List<String> names = new ArrayList<>(Arrays.asList("Negotiation","Pyschology","Joke"));
for (int i = 0; i<3;++i){
TextView dynamic = new TextView(this);
dynamic.setText(names.get(i));
dynamic.setTextSize(14);
dynamic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
ll.addView(dynamic);
}
}
}
The result is a blank page and what I want is three clickable textviews as the result. Where did I go wrong?

If I am not wrong sir you want to add Text view Programmatically
Find you need a layout parent layout Your parent layout is Linear layout set id of a linear layout Suppose id is linerlayout_parent After this in Activity
LinearLayout linearview = findViewById(R.id.linerlayout_parent);
Now Here Create text view Programatically
TextView title=new TextView(Activity.this);
title.setTextSize(20);
title.setTextAppearance(context,R.font.abhaya_libre_bold);
title.setPadding(10,10,10,10);
title.setTextColor(Color.BLACK);
title.setText("Hello use this code");
linearview.addView(title);
if you need three than in Loop paste this code
Kindly set orientation of a Linear layout Vertical

May be you forgot to add textview in parentview like this.
tv[i] = new TextView(this);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.topMargin = i*50;
tv[i].setText(str[i]);
tv[i].setTextSize((float) 20);
tv[i].setPadding(20, 50, 20, 50);
tv[i].setLayoutParams(params);
rl.addView(tv[i]);

Related

How to add images when using spinner

I am a beginner at using Android Studio Java, I have been assigned to make a dropdown list with all the car names. I have to include 30 car images but to start things off I am trying to include 5 images, I have been trying to add an image on each of the cars that are on the dropdown list. I figured out how to do the spinner and I have the code for it but now when I click on the dropdown list and click the Ford car and I want the images to appear as well.
For the main.java (called Activity2.java) here is the code for it
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Activity2 extends AppCompatActivity {
private Spinner carsSpinner;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
carsSpinner = findViewById(R.id.carsSpinner);
//final ArrayList<String> cars = new ArrayList<>();
// cars.add("Audi");
// cars.add("Bentley");
// cars.add("BMW");
// cars.add("Chevrolet");
//cars.add("Citroen");
//ArrayAdapter<String> carsAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_dropdown_item, cars);
//carsSpinner.setAdapter(carsAdapter);//
carsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Activity2.this, carsSpinner.getSelectedItem().toString() + " Selected",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
For the main activity.xml (called activity2.xml) here is the code for it, I know I have to include the ImageView there.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:id="#+id/carsSpinner"
android:entries="#array/cars"/>
</RelativeLayout>
For the string.xml here is the code for it
<resources>
<string name="app_name">My Application</string>
<string-array name="cars">
<item>Audi</item>
<item>Bentley</item>
<item>BMW</item>
<item>Ferrari</item>
<item>Citroen</item>
</string-array>
This is how my application is looking but now I want to include the car image for each car on it, it will mean a lot if you guys could show me through the right direction.
You have to make a custom layout and adapter.
More information on how to implement it on the link below:
https://www.codingdemos.com/android-custom-spinner-images-text/

ANDROID fragment is not able to add or replace with new fragment

i have tried the all the suggestions for this. All that answers are changing the fragment from a activity but here is the difference in my question. i am trying to change one fragment to another fragment from the first fragment.Please help me .
i have a fragment which contains dynamic buttons.please find the image [![enter image description here][1]][1]
If the user clicks any of the button i want to show some stack cars for the same.see the image [![enter image description here][2]][2]
Ok this is my requirement. My problem is i have one activity which contains the bottom navigation bar names as ShowDashBoardActivity
ShowDashBoardActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.yourname.R;
import com.yourname.fragments.DashBoardJobList;
import com.yourname.fragments.DashBoardOne;
import com.yourname.fragments.DashBoardTaskBubble;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarFragment;
import butterknife.Bind;
public class ShowDashBoardActivity extends AppCompatActivity {
private BottomBar bottomBar;
LinearLayout CardAspirationLayout,TextCardAspirationLayout;
DashBoardOne _DashBoardOne;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_dash_board_activity);
context=getApplicationContext();
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
View view =getSupportActionBar().getCustomView();
/*ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});*/
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
new BottomBarFragment(DashBoardOne.newInstance("Content for Dashboard."), R.drawable.dashboard, "Dashboard"),
new BottomBarFragment(DashBoardTaskBubble.newInstance("Content for Task."), R.drawable.task, "Task"),
new BottomBarFragment(DashBoardJobList.newInstance("Content for Job."), R.drawable.job, "Job")
);
TextCardAspirationLayout=(LinearLayout) findViewById(R.id.TextCardAspirationLayout);
bottomBar.setActiveTabColor("#C2185B");
BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(2, "#E91E63", 4);
unreadMessages.show();
unreadMessages.setAnimationDuration(200);
unreadMessages.setAutoShowAfterUnSelection(true);
// bottomBar.useDarkTheme(true);
}
}
show_dash_board_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/slidetwo"
xmlns:tools="http://schemas.android.com/tools" >
</FrameLayout>
The navigation drawer is working perfect. the in the DashBoardTaskBubble.java it is fragment i am drawing dynamic bubble to show like picture 1.
DashBoardTaskBubble.java
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.panenviron.R;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.tint;
public class DashBoardTaskBubble extends Fragment {
private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
public DashBoardTaskBubble() {
}
public static DashBoardTaskBubble newInstance(String text) {
Bundle args = new Bundle();
args.putString(STARTING_TEXT, text);
DashBoardTaskBubble dashBoardTaskBubble = new DashBoardTaskBubble();
dashBoardTaskBubble.setArguments(args);
return dashBoardTaskBubble;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_bubble, container, false);
final RelativeLayout workViewLayout = (RelativeLayout)view.findViewById(R.id.workView);
int iNumberOfButtons = 6; // no of bubble create function to fetch no of bubble from db
// create a function to get color from db now give static
String[] colourList = new String[] { "#ffaa00","#32CD32","#0000FF"};
Button[] dynamicButtons = new Button[iNumberOfButtons];
List<String> tempColouersList= new ArrayList<String>();
for (int i = 0; i < iNumberOfButtons; i++) {
dynamicButtons[i] = new Button(getActivity());
dynamicButtons[i].setText("+"+i+5);
dynamicButtons[i].setId(i);
dynamicButtons[i].setTextSize(15.0f);
dynamicButtons[i].setBackgroundResource(R.drawable.round_button);
if(i==0){
RelativeLayout.LayoutParams paramsButton =
new RelativeLayout.LayoutParams(350,350);
paramsButton.setMargins(50,0,0,0);
dynamicButtons[0].setLayoutParams(paramsButton);
tempColouersList.add(colourList[0]);
} else if(i==1){
RelativeLayout.LayoutParams paramsButton2 =
new RelativeLayout.LayoutParams(350,350);
paramsButton2.setMargins(700,10,0,0);
dynamicButtons[1].setLayoutParams(paramsButton2);
tempColouersList.add(colourList[1]);
} else if(i==2){
RelativeLayout.LayoutParams paramsButton3 =
new RelativeLayout.LayoutParams(350,350);
paramsButton3.setMargins(400,250,0,0);
dynamicButtons[2].setLayoutParams(paramsButton3);
tempColouersList.add(colourList[2]);
} else if(i==3){
RelativeLayout.LayoutParams paramsButton4 =
new RelativeLayout.LayoutParams(350,350);
paramsButton4.setMargins(50,450,0,0);
dynamicButtons[3].setLayoutParams(paramsButton4);
tempColouersList.add(colourList[1]);
} else if(i==4){
RelativeLayout.LayoutParams paramsButton5 =
new RelativeLayout.LayoutParams(350,350);
paramsButton5.setMargins(700,500,0,0);
dynamicButtons[4].setLayoutParams(paramsButton5);
tempColouersList.add(colourList[2]);
}else if(i==5){
RelativeLayout.LayoutParams paramsButton6 =
new RelativeLayout.LayoutParams(350,350);
paramsButton6.setMargins(350,700,0,0);
dynamicButtons[5].setLayoutParams(paramsButton6);
tempColouersList.add(colourList[0]);
}
ColorStateList tint = new ColorStateList(new int[][]{new int[0]}, new int[]{Color.parseColor(tempColouersList.get(i)) });
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && dynamicButtons[i] instanceof AppCompatButton) {
((AppCompatButton) dynamicButtons[i]).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(dynamicButtons[i], tint);
}
dynamicButtons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Log.e("im on","button clik");
} catch (Exception e) {
e.printStackTrace();
}
}
});
workViewLayout.addView(dynamicButtons[i]); // dynamicButtonsLinearLayout is the container of the buttons
}
return view;
}
public void replaceFragments( ) {
Log.e("im on","replaceFragments");
//Fragment fragment = null;
try {
//fragment = (Fragment) TaskCardListShow.newInstance();
/*TaskCardListShow nextFrag= new TaskCardListShow();
this.getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, nextFrag)
.addToBackStack(null)
.commit();*/
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = https://i.stack.imgur.com/J75iJ.pngmFragmentManager.beginTransaction();
TaskCardListShow mFragment = new TaskCardListShow();
//mFragmentTransaction.replace(R.id.fragmentContainer, mFragment);
mFragmentTransaction.add(R.id.fragmentContainer, mFragment);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
} catch (Exception e)
{ e.printStackTrace(); }
// Insert the fragment by replacing any existing fragment FragmentManager
// fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
}
fragment_task_bubble.xml
<LinearLayout 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:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/slidetwo">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="12"
android:background="#color/white">
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="88"
android:orientation="vertical"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="3dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20dp">
<View
android:layout_width="98dp"
android:gravity="center_horizontal"
android:layout_height="4dp"
android:background="#android:color/holo_red_dark"
android:id="#+id/normalViewSeparator"
/>
</LinearLayout>
<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="wrap_content"
android:layout_weight="30"
android:orientation="vertical"
android:id="#+id/workView"
android:background="#color/white">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
The bubble drawing is also working perfect. Here i trying to add some features like if a user clicks a button i want to show the stack cards like picture 2
I am thinking to display the task cards in fragment . I dont know how to navigate one fragment to another fragment.
TaskCardListShow.java FRAGMENT
package com.panenviron.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.panenviron.R;
public class TaskCardListShow extends Fragment {
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
Log.e("im on","TaskCardListShow");
return view;
}
}
task_card_list_show.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="match_parent"
android:id="#+id/fragment_task_card_list_show"
style="#style/Animation.AppCompat.Dialog">
<TextView
android:text="Im on task fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_weight="1" />
</LinearLayout>
i tried the above replaceFragments( ) custom function. But it is replaces the fragment but it is not removing the first fragment. How can do this.
Your are using support fragments (android.support.v4.app.Fragment) with native fragmentmanager - Activity.getFragmentManager(). Instead you have to use support fragmentmanager - AppCompatActivity.getSupportFragmentManager().
I really wish android tools would handle this annoying situation better.
inside the fragment you have to call getActivity().getSupportFragmentManager() instead of getFragmentManager. so you have to give like this "getActivity().getSupportFragmentManager().beginTransaction()" in the fragment transaction. after that you can replace simply like already done

Unable to dynamically add TextView when java class extends AppCompatActivity

I am trying to add a TextView dynamically to my activity, but when i run the app it is not showing up. There are no errors, and the app does not crash, but the TextView does not show up. My java class extends AppCompatActivty, and i noticed that when i change it to extending Activity my code works, and the TextView shows up. My question is, why does the following code work for Activity but not AppCompatActivity?
My java class FormActivty.java
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}
My XML activity_form.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/formLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/container"
android:orientation="vertical"></LinearLayout>
</LinearLayout>
I am not sure why this is the case, but if i remove PersistableBundle persistentState from the onCreate method, then it works. my java class now looks like
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}

Adding views to another line (another LinearLayout)?

So I'm creating a small application, and thanks to this site, I've progressed on it a lot more. The idea of it is that I will just have a button, and when it is clicked, it will add a new row with two "EditText" and one "CheckBox". I've somewhat accomplished this through dynamically adding these with a custom ListView and a custom adapter. I'm still iffy on custom ListView's and adapters.
Anyways, I've gotten it to add the two EditText and one CheckBox when the button is clicked, but it will not add any more after this (this is a separate problem though). The problem I'm having, is that it will add them on the same row as the button. This is where I get lost. I'm not sure how to get this custom ListView to display on a new row, rather than the same row as the button.
Now, here is my MainActivity code:
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.view.ViewGroup.LayoutParams;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<CheckBox> checkBoxes = new ArrayList<>();
ArrayList<EditText> courses = new ArrayList<>();
ArrayList<EditText> credits = new ArrayList<>();
int numOfCheckBoxes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button addCourse = new Button(this);
addCourse.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addCourse.setText("Add Course");
addCourse.setTextColor(Color.parseColor("#FFFFFF"));
addCourse.setBackgroundColor(Color.parseColor("#FF0000"));
addCourse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListView myListView = new ListView(MainActivity.this);
List<CustomRow> rows = new ArrayList<CustomRow>();
rows.add(new CustomRow(MainActivity.this));
MyListArrayAdapter myAdapter = new MyListArrayAdapter(MainActivity.this, rows);
myListView.setAdapter(myAdapter);
ll.addView(myListView);
}
});
ll.addView(addCourse);
} // End of onCreate
public void onCheckBoxChecked(View v) {
for (int i = 0; i < numOfCheckBoxes; i++) {
if (checkBoxes.get(i).isChecked()) {
courses.get(i).setEnabled(false);
courses.get(i).setFocusable(false);
courses.get(i).setInputType(InputType.TYPE_NULL);
credits.get(i).setEnabled(false);
credits.get(i).setFocusable(false);
credits.get(i).setInputType(InputType.TYPE_NULL);
} else {
courses.get(i).setEnabled(true);
courses.get(i).setFocusable(true);
courses.get(i).setFocusableInTouchMode(true);
courses.get(i).setInputType(InputType.TYPE_CLASS_TEXT);
credits.get(i).setEnabled(true);
credits.get(i).setFocusableInTouchMode(true);
credits.get(i).setFocusable(true);
credits.get(i).setInputType(InputType.TYPE_CLASS_NUMBER);
} // End of if else
} // End of for loop
} // End of onCheckBoxChecked
} // End of MainActivity
Here is my "MyListArrayAdapter" class (my custom adapter):
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.List;
/**
* Created by Thomas on 5/21/2016.
*/
public class MyListArrayAdapter extends BaseAdapter {
LayoutInflater inflater;
List<CustomRow> rows;
public MyListArrayAdapter(Activity context, List rows){
super();
this.rows = rows;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return rows.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomRow row = rows.get(position);
View v = convertView;
if (convertView==null) {
v = inflater.inflate(R.layout.new_course_row, null);
}
EditText course = (EditText) v.findViewById(R.id.course);
EditText credits = (EditText) v.findViewById(R.id.credits);
CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
course.setHint("Enter Course");
credits.setHint("Enter Credits");
checkBox.setText("Check if complete");
course.setMaxHeight(150);
credits.setMaxHeight(150);
checkBox.setMaxHeight(150);
return v;
}
}
My "CustomRow" class (the custom class with the two EditText and one CheckBox):
import android.content.Context;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
/**
* Created by Thomas on 5/21/2016.
*/
public class CustomRow extends LinearLayout{
public CustomRow(Context context) {
super(context);
setOrientation(LinearLayout.HORIZONTAL);
EditText course = new EditText(context);
EditText credits = new EditText(context);
CheckBox checkBox = new CheckBox(context);
addView(course);
addView(credits);
addView(checkBox);
}
}
My "new_course_row.xml" file:
<?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="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/course"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/credits"
android:layout_weight="1"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onCheckBoxChecked"/>
</LinearLayout>
Lastly, my "activity_main.xml":
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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="exporian.collegetracker.MainActivity"
android:id="#+id/ll">
</LinearLayout>
</ScrollView>
Thank you in advance everyone! I've been stuck here for a few days. Not looking for anyone to write the app for me, just looking for some direction.
make sure that after adding a button you have called these two methods in your adapter to update the list
BuddyFeedsAdapter.this.notifyDataSetChanged();
notifyDataSetInvalidated();
If your code is working properly and adding row on same row, then please check below solution.
As you have write below line ,
List<CustomRow> rows = new ArrayList<CustomRow>();
in OnButton CLick event, so whenever button will be clicked, it will initialise rows again and remove all previous records from it, so just write above line at top or in onCreate() method after setContentView, then you will get all rows on click.
Hope this will help you.

Error using relative layout using code

I am getting java.lang.IllegalStateException while using relative layout using code. I know how to use relative layout using xml, but I have to use it using code only.
Here is my code:
package com.example.pr;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ProfessionalProfileTab extends Fragment
{
EditText regNumber,medCouncil,languages,degree,course,year,speciality,
experience_start_month,experience_end_month,designation,experience_company;
TextView regNumberText,medCouncilText,languagesText,degreeText,specialityText,experienceText;
ImageButton addDegree;
Button updateProfession;
Display display;
double width,height;
private int mYear, mMonth, mDay;
Context con;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
display = getActivity().getWindowManager().getDefaultDisplay();
width = MainActivity.Parentwidth;
height = MainActivity.Parentheight;
Log.d("Inside Professional Profile Fragment","ppsg");
Log.d("width",String.valueOf(width));
Log.d("height",String.valueOf(height));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.professional_profile_tab, container, false);
con = container.getContext();
final LinearLayout layout=(LinearLayout)view.findViewById(R.id.professionalProfileDetails);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
final RelativeLayout rlayout=(RelativeLayout)view.findViewById(R.id.reldegree) ;
final RelativeLayout.LayoutParams rparam=new RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT) ;
final TextView degreeText=new TextView(con);
degreeText.setTag("degreeText");
degreeText.setText("degree:");
layout.addView(degreeText);
rlayout.addView(degreeText);
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(params);
degreeText.setLayoutParams(rparam);
final ImageButton addDegree=new ImageButton(con);
addDegree.setTag("addDegree");
addDegree.setImageResource(R.drawable.ic_launcher);
layout.addView(addDegree);
rlayout.addView(addDegree);
rparam.addRule(RelativeLayout.BELOW,addDegree.getId());
degreeText.setLayoutParams(params);
addDegree.setLayoutParams(rparam);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}
Here is the xml version of what I want from my code:
<LinearLayout
android:id="#+id/professionalProfileDetails"
android:layout_width="320dp"
android:layout_height="200dp"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/reldegree"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/degreeText"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Degree Details"/>
<ImageButton
android:id="#+id/addDegree"
android:layout_toRightOf="#id/degreeText"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
</LinearLayout>
Here I want to set the image to the right of degreetext textField.
I have tried to search for a solution to this problem, but could not find any.
Can we use relative layout in the same way as we do in xml and set layout:toRightOf or toLeftOf or below etc using code for texts or images.
You are trying to add the same View to 2 different ViewGroups which is not possible.
layout.addView(degreeText);
rlayout.addView(degreeText);
Also, you are trying to position a View below itself.
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(rparam);
**Try this**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<RelativeLayout
android:id="#+id/layoutContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
</RelativeLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
RelativeLayout layoutContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutContainer = (RelativeLayout)
findViewById(R.id.layoutContainer);
final TextView degreeText=new TextView(this);
degreeText.setId(1);
degreeText.setText("degree:");
layoutContainer.addView(degreeText);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, degreeText.getId());
final ImageButton addDegree=new ImageButton(this);
addDegree.setImageResource(R.drawable.ic_launcher);
addDegree.setLayoutParams(params);
layoutContainer.addView(addDegree);
}
}

Categories

Resources