LayoutInflater not Updating the View Property - java

I am simply using LayoutInflater to get A View(Button) From a layout.xml file other then the activity_main.xml. but When I change the setText("") property of the button the button property does not updates.
I am checking if I can change the text property of the button element in the testlayout.xml But when I set the property of the Button in onCreate and when I check for that property in call that was not changed...
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.testlayout, null);
Button btn = (Button)linearLayout.findViewById(R.id.testbtn);
btn.setText("Hello");
}
public void call(View v){
Button btn = (Button)findViewById(R.id.testBtn);
Toast.makeText(this, btn.getText(), Toast.LENGTH_SHORT).show();
}
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"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/mainBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="73dp"
android:text="Button"
android:onClick="call"
/>
</RelativeLayout>
testlayout.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:orientation="vertical" >
<Button
android:id="#+id/testBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

You need to add this linearlayout to your activity:
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.testlayout, null);
Button btn = (Button)linearLayout.findViewById(R.id.button1);
btn.setText("Hello");
RelativeLayout rl=findViewById(R.id.root);
rl.addView(linearLayout);

You need to add testlayout.xml as a child to the activity view using ViewGroup.addView(View child) method. Currently you see the button from the first layout. What are you trying to do ?

You need to add the other xml to your current view :-
package com.example.testdynamicviews;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout main = (LinearLayout)findViewById(R.id.mainView); // Your custom view will be added in this layout
TextView text = myView();
text.setText("Rahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul Gupta");
main.addView(text); // You forgot to add this line
Button button = myCustomButton();
button.setText("Custom Button");
main.addView(button);
}
public TextView myView(){
View v;
LayoutInflater li = LayoutInflater.from(getBaseContext());
v = li.inflate(R.layout.textview, null);
int width = (int) (getResources().getDimension(R.dimen.testwidth)/ getResources().getDisplayMetrics().density);
v.setLayoutParams(new LinearLayout.LayoutParams(width,LinearLayout.LayoutParams.WRAP_CONTENT));
return (TextView) v;
}
public Button myCustomButton(){
View v;
LayoutInflater li = LayoutInflater.from(getBaseContext());
v = li.inflate(R.layout.custombutton, null);
v.setBackgroundColor(Color.RED);
int width = (int) (getResources().getDimension(R.dimen.testwidth)/ getResources().getDisplayMetrics().density);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 10, 0, 0);
v.setLayoutParams(params);
return (Button) v;
}
#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;
}
}
textview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="sgfiughbjkh"
android:singleLine="true"
android:textSize="#dimen/testsize"
android:background="#android:color/holo_blue_bright"
android:ellipsize="end" >
</TextView>
custombutton.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_bright"
android:text="sgfiughbjkh"
android:textSize="#dimen/testsize" />

Related

How to add listView with scroll inside a Popup window in android studio?

I am trying to make an android app which opens a popup window when clicked on a button. And, the popup window has four TextView with heading and 4 listView with options. However, I could not add listView inside a popup window. The popup window opens when clicking a button but when I add listView and its adapter and try to run it, the app crashes. I want the layout of PopUp window to be as one in news.xml file.
activity_main.xml
<ScrollView 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:fillViewport="true"
android:visibility="visible"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linear">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/news1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="15dp"
android:text="#string/news" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
MainActivity.java
package com.example.abina.popup;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import static android.view.Gravity.NO_GRAVITY;
public class MainActivity extends AppCompatActivity {
private Button news1;
private PopupWindow popupWindow;
private LayoutInflater layoutInflater;
private LinearLayout linearLayout;
ListView lst;
String [] local = {"asdf","Sgadf","adfhtr","trdbfa"};
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for listView 1
lst = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,local);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,local[i],Toast.LENGTH_SHORT).show();
}
});
linearLayout = (LinearLayout) findViewById(R.id.linear);
news1 = (Button) findViewById(R.id.news1);
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplication().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.news,null);
popupWindow = new PopupWindow(container,800,1300,true);
popupWindow.showAsDropDown(news1);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return false;
}
});
}
});
}
}
news.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ABEBC6">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<ListView
android:id="#+id/listView1"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView"
android:layout_marginStart="13dp" />
<TextView
android:id="#+id/textView"
android:layout_width="109dp"
android:layout_height="33dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="#string/local" />
<TextView
android:id="#+id/textView2"
android:layout_width="108dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/textView"
android:layout_marginEnd="30dp"
android:text="#string/national" />
<ListView
android:id="#+id/listView2"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/listView1" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="260dp">
<TextView
android:id="#+id/textView3"
android:layout_width="109dp"
android:layout_height="33dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="#string/sports1" />
<TextView
android:id="#+id/textView4"
android:layout_width="108dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginEnd="43dp"
android:text="#string/sports2" />
<ListView
android:id="#+id/listView3"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView3"
android:layout_marginStart="20dp" />
<ListView
android:id="#+id/listView4"
android:layout_width="162dp"
android:layout_height="184dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/textView4" />
</RelativeLayout>
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">Popup</string>
<string name="news">Check Latest News!</string>
<string name="local">Local News</string>
<string name="national">National News</string>
<string name="sports1">Sports One</string>
<string name="sports2">Sports Two</string>
<string-array name="local">
<item>Star Ledger</item>
<item>Ny Times</item>
<item>The Record</item>
<item>Trentorian</item>
</string-array>
</resources>
The problem is that your list doesn't exist in your activity_main layout. Rather it exists in popup window.
change your onCreate() method as the code below and it should work fine.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for listView 1
linearLayout = (LinearLayout) findViewById(R.id.linear);
news1 = (Button) findViewById(R.id.news1);
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplication().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.news,null);
popupWindow = new PopupWindow(container,800,1300,true);
lst = container.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,local);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,local[i],Toast.LENGTH_SHORT).show();
}
});
popupWindow.showAsDropDown(news1);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return false;
}
});
}
});
}
Hope this helps you.
Best regards,
In your action listener add this one:
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupWindow popupWindow = new PopupWindow(getApplicationContext());
ArrayList<String> sortList = new ArrayList<>();
sortList.add("A to Z");
sortList.add("Z to A");
sortList.add("Any");
sortList.add("Test");
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
sortList);
ListView listViewSort = new ListView(getApplicationContext());
listViewSort.setAdapter(adapter);
// set on item selected
listViewSort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),
"You select in popup menu" + adapterView.getAdapter().getItem(i).toString(), Toast.LENGTH_LONG).show();
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(listViewSort);
popupWindow.showAsDropDown(view, 0, 0);
});
}
Here example popup menu with two listviews and textviews:
PopupWindow popupWindow = new PopupWindow(getApplicationContext());
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_element,
(ViewGroup) view, false);
//List first
TextView nameOfList1 = layout.findViewById(R.id.text1);
nameOfList1.setText("List one:");
ListView mListView1 = layout.findViewById(R.id.listView1);
final String[] data1 = {"Value from list 1", "Value from list 2", "Value from list 3", "Value from list 4",
"Value from list 5", "Value from list 6"};
mListView1.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, data1));
mListView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You select value from list one " + data1[i], Toast.LENGTH_LONG).show();
}
});
//List second
TextView nameOfList2 = layout.findViewById(R.id.text2);
nameOfList2.setText("Select planet from list");
ListView mListView2 = layout.findViewById(R.id.listView2);
final String[] data2 = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
mListView2.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, data2));
mListView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You select plane " + data2[i], Toast.LENGTH_LONG).show();
}
});
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(layout);
popupWindow.showAsDropDown(view, 0, 0);
And popup_element.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollojt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f00"></ListView>
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ListView
android:id="#+id/listView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/listView1"
android:background="#0f0"></ListView>
</LinearLayout>
</ScrollView>

Same Fragment Should Appear one below another according to the Number Selected in Spinner. HOW?

I have a Small Fragment with three EditText and i have a Spinner with 1,2,3 as options in It.
What i want to do is that, when i select '1' from the Spinner, i want my fragment to appear below the spinner in same Activity.
And when i select '2' in Spinner, the same Fragment Should Appear Twice one below another in the same Activity and similarly for when i select '3' from Spinner.
HERE IS THE JAVA CODE
package com.globaltech2u.databaseapp1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String bookno[] = {"#","1","2","3","4"};
private ArrayAdapter<String> arrayAdapter;
private EditText editText,editText2,editText3;
private CheckBox checkBox;
private Button button;
private SQLiteDatabase db;
private Database mySQLiteOpenHelper;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.et1);
editText2 = (EditText)findViewById(R.id.et2);
editText3 = (EditText)findViewById(R.id.et3);
checkBox = (CheckBox)findViewById(R.id.cb1);
button = (Button)findViewById(R.id.button);
spinner = (Spinner)findViewById(R.id.booknoselectspinner);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, bookno);
spinner.setAdapter(arrayAdapter);
mySQLiteOpenHelper = new Database(this, "bookrecord", null, 1);
db = mySQLiteOpenHelper.getWritableDatabase();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String bookname = editText.getText().toString();
String bookno = editText2.getText().toString();
String issuedate = editText3.getText().toString();
String query = "insert into bookrecord(bookname,bookno,issuedate) values('"+bookname+"','"+bookno+"','"+issuedate+"')";
Log.e("query",query);
db.execSQL(query);
Toast.makeText(MainActivity.this, "inserted", Toast.LENGTH_SHORT).show();
}
});
final FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
for (int j=0;j<=i;j++){
BookentryFragment bookentryFragment = new BookentryFragment();
fragmentTransaction.replace(android.R.id.content, bookentryFragment);
}
fragmentTransaction.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
HERE IS THE MAIN ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select No. of Books Issued"
android:id="#+id/tv4"
android:layout_centerHorizontal="true"
android:textColor="#color/colorAccent"
android:textSize="19dp"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/booknoselectspinner"
android:layout_toRightOf="#+id/tv4"
>
</Spinner>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/FM1"
android:layout_below="#+id/tv4"
android:orientation="vertical"
>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Record"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button"
android:layout_below="#+id/FM1"
/>
</RelativeLayout>
HERE IS THE FRAGMENT FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/border">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:hint="Enter Book Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:layout_below="#+id/booknoselectspinner"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et2"
android:hint="Enter Book No."
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et1"
android:layout_centerHorizontal="true"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et3"
android:inputType="date"
android:hint="Select Issue Date"
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et2"
android:layout_centerHorizontal="true"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me to Return"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:id="#+id/cb1"
android:layout_below="#+id/et3"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
LET ME KNOW IF I SHOULD ATTACH SOMETHING ELSE
I TRIED TO USE WHILE LOOP BUT THE APP CRASHES. PLEASE HELP
THANK YOU
I tried it with this Layout Inflater Code.
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
It adds the Fragment once when i open the Activity.
But when i select 2 from the spinner, Nothing Happens.
I am using Switch Case for this Purpose
switch (i) {
case 0:
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
break;
case 1:
FrameLayout item2 = (FrameLayout) findViewById(R.id.FM1);
View child2 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item2.addView(child2);
FrameLayout item3 = (FrameLayout) findViewById(R.id.FM1);
View child3 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item3.addView(child3);
break;
case 2:
FrameLayout item4 = (FrameLayout) findViewById(R.id.FM1);
View child4 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item4.addView(child4);
FrameLayout item5 = (FrameLayout) findViewById(R.id.FM1);
View child5 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item5.addView(child5);
FrameLayout item6 = (FrameLayout) findViewById(R.id.FM1);
View child6 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item6.addView(child6);
break;
}
Make the FrameLayout a class object, and initialize it using (FrameLayout) findViewById(R.id.FM1); only once, outside the switch statement.
In each of your case blocks, add this piece of code in the beginning:
if(item.getChildCount()>0){
item.removeAllViews();
}
EDIT: Your spinner's onItemSelected would be something like:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
item.removeAllViews();
for (int j=0;j<=i;j++){
View v = getLayoutInflater().inflate(R.layout.fragmentXML, null);
item.addView(v);
}
}

onClickListener on imageview to start new intent

So Im trying to use an onClickListener to pass an image from one activity to a new activity but I cannot figure out how to do it. How it works is the app starts with a listview where you can select an item and it opens a new activity that displays some information and an image below. I want to be able to click the image to open it in a new activity.
Heres my routeDetails.java this is where the image I want to click is located
package com.example.zach.listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import static com.example.zach.listview.R.id.image;
public class RouteDetails extends AppCompatActivity {
TouchImageView routeImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);
//back button for route details view
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getString("route"));
//ImageView for route details
routeImage = (TouchImageView) findViewById(R.id.routeImage);
routeImage.setImageResource(getIntent().getIntExtra("imageResourceId", 0));
////////// Trying to pass image to new activity
routeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int imageId = (int) image.getResourceId(i, -1);
Intent intent = new Intent(v.getContext(), FullScreenImage.class);
intent.putExtra("imageResourceId", imageId);
startActivity(intent);
}
});
////////////
}
//back button for route details view
#Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
}
and heres the activity_route_details.xml that goes with it
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_route_details"
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="com.example.zach.listview.RouteDetails">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/routeDetailsView"
android:textSize="18sp"
android:textAlignment="center" />
<com.example.zach.listview.TouchImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/routeImage"
android:scaleType="fitCenter"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:adjustViewBounds="false"
android:layout_below="#+id/routeDetailsView"/>
</RelativeLayout>
</ScrollView>
heres my FullScreenImage.java that I want the image to open in
package com.example.zach.listview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Zach on 11/15/2016.
*/
public class FullScreenImage extends AppCompatActivity {
TouchImageView routeImage;
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.full_screen_image);
routeImage = (TouchImageView) findViewById(R.id.fullScreenImageView);
routeImage.setImageResource(getIntent().getIntExtra("imageFullScreen", 0));
}
}
And heres the full_scren_image.xml to go with it
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.zach.listview.TouchImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#+id/routeImage"
android:id="#+id/fullScreenImageView"
android:layout_weight="1" />
</LinearLayout>
You're putting in the extra with the key imageResourceId but you're trying to pull it out with the key imageFullScreen. Try using the same key in both places.
Use your image as ByteArray. This worked for me without any problem. In your click listener of the sender activity do the following,
Intent senderint = new Intent(context, receiveractivity.class);
Bitmap bitmap = drawableToBitmap(view.getBackground());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = baos.toByteArray();
senderint.putExtra("myimage", b);
startActivity(senderint);
And in your receiver activity do the following.
private void getImage(){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = null;
v = inflater.inflate(R.layout.receiverlayout, null);
ViewGroup vg = (ViewGroup) findViewById(R.id.yourmainlayout);
Bundle bundle = getIntent().getExtras();
byte[] ba = bundle.getByteArray("myimage");
Bitmap bm = BitmapFactory.decodeByteArray(ba, 0, ba.length());
Drawable dr = new BitmapDrawable(getResources, bm);
vg.setBackground(dr);
vg.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
call getImage() in your oncreate method of your receiver activity. The context is your application context. Good luck:)

Can't work out how to get an image to display in a Listview

I've watched videos, search stack overflow and tried to implement what i have learnt into my code, but i just can't get the Listview to display an image to the right.
Here is my page1.xml (which contains the listview):
<?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:orientation="vertical"
android:background="#ffd9d9d9">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center"
android:dividerHeight="8dip"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:scrollbars="none"
android:clipToPadding="false"
/>
</LinearLayout>
Here is my custom row.xml (which is working flawlessly)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowtext"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical"
android:textColor="#ff858585"
android:textSize="20sp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:minHeight="80dp"
android:background="#drawable/card"/>
And here is my Backups.java:
package com.YvesB.tobin;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
public class Backups extends Activity {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.RedTheme);
setContentView(R.layout.page1);
ActionBar ab = getActionBar();
ab.setHomeButtonEnabled(true);
ab.setDisplayHomeAsUpEnabled(true);
ListView listView1 = (ListView) findViewById(R.id.listView);
File directory = new File(extStorageDirectory
+ "/Android/data/com.tobin.redirect");
String[] filenames = directory.list();
if (filenames == null){
}
else{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, filenames);
listView1.setAdapter(adapter);
}
}
}
Thanks for the help, the png i want to sue is called drive.png !
On a side note, you guys are all awesome, going out of your way to help others!
The first thing to do is to change your row.xml. It should contain an ImageView that displays your drive.png. Something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowtext"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical"
android:textColor="#ff858585"
android:textSize="20sp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:minHeight="80dp"
android:background="#drawable/card"/>
<ImageView
android:id="#+id/drive"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginLeft="5px"
android:layout_marginRight="20px"
android:layout_marginTop="5px"
android:src="#drawable/drive" >
</ImageView>
</LinearLayout>
Then you need to write a custom ArrayAdapter, something like:
public class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyArrayAdapter(Context context, String[] values) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.rowtext);
ImageView imageView = (ImageView) rowView.findViewById(R.id.drive);
textView.setText(values[position]);
// Change icon based on name or position
// ...
return rowView;
}
}
Then you have to use this custom adapter instead of the standard ArrayAdapter<String>.
Examples are taken (and a bit customized) from this Tutorial:
http://www.mkyong.com/android/android-listview-example/
Hope it helps and does what you have in mind.

Show an Image and Text in a ListView

I'm developing an App, that shows a ListView with 30 items.
In each row, there should be a text and an Image.
I searches for different tutorials, but unfortunately all don't work for me.
So I'm asking you to have a short look to my code and tell me what's wrong in there, because when I start the app, the ListView is empty.
mainActivity.java:
setContentView(R.layout.auswertung);
ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(new MyListAdapter(this, fragen));
MyListAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<Frage>{
private final Context context;
private ArrayList<Frage> fragen;
public MyListAdapter(Context context, ArrayList<Frage> f) {
super(context, R.layout.reihe);
this.context = context;
fragen = f;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if(rowView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.reihe, parent, false);
}
TextView textView = (TextView) rowView.findViewById(R.id.textView4);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img1);
textView.setText("Frage " + (position+1));
if (fragen.get(position).getRichtig()==true)
{
imageView.setImageResource(R.drawable.richtig);
}
else
{
imageView.setImageResource(R.drawable.falsch);
}
return rowView;
}
}
auswertung.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"
android:layout_weight="0.96"
android:background="#drawable/hintergrund"
android:orientation="vertical" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginTop="19dp"
android:text="Auswertung"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="460dp"
android:layout_marginTop="60dp">
</ListView>
</RelativeLayout>
reihe.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/textView4"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="5"
android:textSize="16dp"
android:textColor="#000000" />
<ImageView
android:id="#+id/img1"
android:layout_width="25dp"
android:layout_height="25dp" />
</LinearLayout>
As you see, I have a background image, and would also ask you, how can I make the background of the ListView invisible, so that I can see my background behind the text and the Image?
you should pass the the ArrayAdapter constructour your Frage data set, or at least,
ovveride ArrayAdapter.getCount(), and let it returns the number of items in ArrayList<Frage> f
int getCount() {
return (f == null) ? 0 : f.size();
}
here the doc for getCount()

Categories