I want to change images in my popupwindow. I am trying to change ImageView image source which is in test.xml while my contentView is activity_main. When I try to just call imageView.setImageResource(android.R.drawable.ic_menu_help); it gives me nullpointerexception I realized i have to use inflate method, but when I use it it doesn't do what I want.I know there is a lot of questions regarding this, but none of them really helped me.
This is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.popupwindow.MainActivity">
<Button
android:text="Test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_dark"
android:id="#+id/test1"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linear1">
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:src="#android:drawable/btn_star_big_on"
android:id="#+id/imageView1"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
my main.java:
public class MainActivity extends AppCompatActivity {
private PopupWindow popupWindow;
private RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button test = (Button) findViewById(R.id.button);
relativeLayout = (RelativeLayout) findViewById(R.id.relative);
final View view1 = getLayoutInflater().inflate(R.layout.test, null);
ImageView imageView = (ImageView) view1.findViewById(R.id.imageView1);
imageView.setImageResource(android.R.drawable.ic_menu_help); //Image source is not changed in my popupWindow,
// but it is changed when I call relativeLayout.addView(view1);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//relativeLayout.addView(view1); // <-- this does the trick, but its not what i want
View container = getLayoutInflater().inflate(R.layout.test, null);
popupWindow = new PopupWindow(container, android.app.ActionBar.LayoutParams.MATCH_PARENT, android.app.ActionBar.LayoutParams.WRAP_CONTENT, true);
popupWindow.showAtLocation(relativeLayout, Gravity.BOTTOM, 0, 0);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
}
});
}
}
You're inflating two separate views. Obviously what you do in one will have no impact on the other. You should set the popup view to your originally inflated view:
popupWindow = new PopupWindow(view1,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT,
true);
Related
In My Activity i have a Edit Text and Button When the user enter the button " Add " the checklist want to create Automatically with the name of the user entered in the edit text
how to create a checkbox in java program based on the user input
when i click the Add Button the list was not updated ( the userinput was not converted into checkbox and it doesnot display the name in bottom )
Here is My XML Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name to Add in the list"
android:id="#+id/ed_name"
android:layout_marginTop="15dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/btn_add"
android:layout_below="#+id/ed_name"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
/>
</RelativeLayout>
here is My java code
public class MainActivity extends AppCompatActivity {
EditText uinput;
Button btnadd;
CheckBox cbname;
ScrollView sv;
RelativeLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = new ScrollView(this);
ll = new RelativeLayout(this);
// ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
uinput = findViewById(R.id.ed_name);
btnadd = findViewById(R.id.btn_add);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = uinput.getText().toString();
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(Name);
ll.addView(cb);
}
});
}
I suggest you to add everything that is static in the activity_main.xml layout file as :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<EditText
android:id="#+id/ed_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:ems="10"
android:hint="Enter name to add in the list"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="Add"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ed_name" />
<ScrollView
android:id="#+id/scrollview"
android:layout_width="409dp"
android:layout_height="612dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_add">
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Now, Checkbox are the one which we will generate programmatically and add them to the LinearLayout which is the only child of ScrollView(it supports single child only). A sample code for MainActivity doing that is here :
public class MainActivity extends AppCompatActivity {
// declare the required views variable
private EditText uInput;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// initializes required view variable
uInput = findViewById(R.id.ed_name);
linearLayout = findViewById(R.id.linear_layout);
Button btnAdd = findViewById(R.id.btn_add);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = uInput.getText().toString();
if (!name.isEmpty()) {
CheckBox checkBox = new CheckBox(MainActivity.this);
checkBox.setText(name);
linearLayout.addView(checkBox);
} else
Toast.makeText(MainActivity.this, "The name cannot be empty!", Toast.LENGTH_LONG).show();
}
});
}
}
It also checks whether or not the text in EditText is empty and if it is generates a suitable Toast message to not permit the user create a empty Checkbox. Hope, this helps!
You didn't add the ScrollView to your layout, So the R.layout.activity_main know nothing about your added views.
So, inflate your root ViewGroup of your layout, add the ScrollView to it and set constraints/attributes according to the type of your root ViewGroup.
Add an id to the root layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/root"
tools:context=".MainActivity">
Replace the ScrollView inner RelativeLayout with a LinearLayout and add the ScrollView with an attribute param RelativeLayout.BELOW to be at the bottom of the btn_add
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
// ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
EditText uinput = findViewById(R.id.ed_name);
Button btnadd = findViewById(R.id.btn_add);
RelativeLayout rootLayout = findViewById(R.id.root);
// Set constraints/attributes to the sv
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, btnadd.getId());
rootLayout.addView(sv, params);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = uinput.getText().toString();
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(Name);
ll.addView(cb);
}
});
This code will add a checkbox in your view
since you don't have any provided code, ill give you an idea to come up on your own strategies or style
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
Button b = new Button(this);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(myTextBoxText.getText());
ll.addView(cb);
}
});
I'm trying to do what the title says, but for some reason the application crashes when I click on the button.
The error it shows is:
java.lang.IllegalStateException: Could not find method show(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'btn_1'
I have a MainActivity that contains a method to open a popupwindow from a button, (which seems to work fine but I'm writting it just in case) and is:
public class MainActivity extends AppCompatActivity{
private PopupWindow popUpWindow;
private LayoutInflater layoutInflater;
private RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout) findViewById(R.id.relative);
}
public void newWindowPopup(View view){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int wide = dm.widthPixels;
int height = dm.heightPixels;
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.activity_popwindow, null);
popUpWindow = new PopupWindow(container, (int)(wide*.7), (int)(height*.25), true);
popUpWindow.setAnimationStyle(R.style.PopupAnimation);
popUpWindow.showAtLocation(relativeLayout, Gravity.CENTER, 0, 0);
container.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
popUpWindow.dismiss();
return true;
}
});
}
Layout for this activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative"
android:background="#A85757"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<GridLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:columnCount="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnFrases"
android:layout_width="10dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="newWindowPopup"
android:text="Button 1"
android:textColor="#000000" />
</LinearLayout>
</GridLayout>
</ScrollView>
</RelativeLayout>
The code for opening the activity from another button from the popwindow class I created, which seems to be where the trouble is:
public class popwindow extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popwindow);
Button p_button=findViewById(R.id.btn_1);
p_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent showActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(showActivity);
}
});
}
public void show(View view) {
Intent showActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(showActivity);
}
}
Layout for this activity:
<?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="#color/colorPrimary">
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal">
<Button
android:id="#+id/btn_1"
android:layout_width="10dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="EEEEE"
android:textColor="#000000" />
</LinearLayout>
</RelativeLayout>
Finally, the activity I'm trying to open from this popwindow (Main2Activity) doesn't have code yet, It's just an empty activity with a TextView.
The methods View are associated to the buttons with the onClick property so that's not the issue. Thank you very much if you can help.
First add a button on popwindow layout.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Second Activity"/>
Then add following function to show popup and move to second activity
public void newWindowPopup(View view){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int wide = dm.widthPixels;
int height = dm.heightPixels;
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popwindow, null);
popUpWindow = new PopupWindow(container, (int)(wide*.7), (int)(height*.25), true);
popUpWindow.setAnimationStyle(R.style.PopupAnimation);
popUpWindow.showAtLocation(relativeLayout, Gravity.CENTER, 0, 0);
container.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
popUpWindow.dismiss();
return true;
}
});
Button p_button=container.findViewById(R.id.button);
p_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent showActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(showActivity);
}
});
}
So I have an app with a listview. When you click a listview item it opens a new activity. I placed a checkbox in this new activity where when its checked, it should put a checkmark next to the listview item on the previous screen. I'm running into this error I'm guessing because I'm trying to set the checkbox from the second activity that has a different content view than the listview. I hope I explained that well.
Heres my RouteDetails.java with the checkbox code
public class RouteDetails extends AppCompatActivity {
ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);
//back button for route details view
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
///////checkbox///////////////////////////////////////////
routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
checkImageView.setImageResource(R.drawable.birdsboroicon);
}
}
});
/////////////////////////////////////////////
//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);
//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));
//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
routeImage.setImageResource(mImageResource);
and heres the custom_row.xml that contains the imageview im trying to set based on the checkbox state.
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="51dp"
android:id="#+id/routeText"
android:layout_weight="1"
android:textSize="18sp"
android:gravity="center_vertical"
android:textColor="#android:color/black"
android:typeface="normal"
/>
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:id="#+id/checkImageView" />
So I want the checkmark to be next to the listview item after the back button is pressed.
Ill include this other code if it is relavent
heres my RouteDetails.xml that contains the checkbox
<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="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="com.example.zach.listview.RouteDetails">
<CheckBox
android:text="Route Climbed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/routeCheckBox"
android:gravity="center" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/routeDetailsView"
android:textSize="18sp"
android:textAlignment="center"
android:textColor="#android:color/black"
android:layout_below="#id/routeCheckBox"/>
<ImageView
android:layout_below="#id/routeDetailsView"
android:layout_width="match_parent"
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="true" />
</RelativeLayout>
</ScrollView>
My Custom adapter.java which creates each listview row
class CustomAdapter extends ArrayAdapter<CharSequence>{
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
return customView;
}
my mainavtivity.java which is where the listview is populated
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Action Bar customization
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayOptions(android.support.v7.app.ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
setContentView(R.layout.activity_main);
///// fill listview numbers I want to add
final String[] routeListviewNumbers = getResources().getStringArray(R.array.routeNumbers);
//fill list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//fills route detail text view with xml array info
final CharSequence[] routeDetail= getResources().getTextArray(R.array.routeDetail);
//fills route detail image view with xml array of images
final TypedArray image = getResources().obtainTypedArray(R.array.routeImages);
//image.recycle();
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CharSequence route = routeListViewItems[position];
int imageId = (int) image.getResourceId(position, -1);
if (route.equals(routeListViewItems[position]))
{
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[position]);
intent.putExtra("imageResourceId", imageId);
intent.putExtra("routeName", routeListViewItems[position]);
startActivity(intent);
}
}
}
);
}
}
and my activitymain.xml which is the listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="0dp"
tools:context="com.example.zach.listview.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/routeListView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Edit: So I added this to my RouteDetails.java
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
//checkImageView.setImageResource(R.drawable.checkmark);
Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
startActivity(check);
}
}
});
and this to my customAdapter.java
////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0));
////////////////////////////////////////
but this is not working either. It says fatal exception unable to find explicit activity class. It's doing this I guess since CustomAdapter is not an activity, but customadapter is linked to my custom_row which contains the imageview I want to add the checkbox to. How would I do this? I'm not sure what else to try
Edit: I still haven't found a solution if anyone has any suggestions!
I've wrote a small application, which shows several android cards. But I'd like to be able to set a colour and title to the top of the card like in the image below, so far I haven't found any information online how to do this. So some help would be fantastic :-)
(My code so far does not accomplish the above, so far my code just produces regular all white cardviews)
My code so far is below:
CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
public List<TTItem> posts = new ArrayList<>();
public void addItems(List<TTItem> items) {
posts.addAll(items);
notifyDataSetChanged();
}
public void clear() {
posts.clear();
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = View.inflate(context, R.layout.item_cardview, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(posts.get(position).title);
Picasso.with(holder.mImageView.getContext()).load(posts.get(position).images[0]).into(holder.mImageView);
}
#Override
public int getItemCount() {
return posts.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ImageView mImageView;
public ViewHolder(View view) {
super(view);
mTextView = (TextView) view.findViewById(R.id.textview);
mImageView = (ImageView) view.findViewById(R.id.imageView);
}
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener {
#InjectView(R.id.mainView)
RecyclerView mRecyclerView;
#InjectView(R.id.refreshContainer)
SwipeRefreshLayout refreshLayout;
private LinearLayoutManager mLayoutManager;
private CardAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mRecyclerView.setHasFixedSize(true);
refreshLayout.setOnRefreshListener(this);
TypedValue tv = new TypedValue();
int actionBarHeight = 0;
if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
refreshLayout.setProgressViewEndTarget(true, actionBarHeight);
mAdapter = new CardAdapter();
mRecyclerView.setAdapter(mAdapter);
// use a linear layout manager
mLayoutManager = new GridLayoutManager(this, 1);
mRecyclerView.setLayoutManager(mLayoutManager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
#Override
public void onRefresh() {
mAdapter.clear();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
refreshLayout.setRefreshing(false);
}
}, 2500);
}
}
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mainView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
item_cardview.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="200dp"
android:layout_height="200dp"
android:padding="10dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding= "5dp"
card_view:cardUseCompatPadding="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"/>
</LinearLayout>
</android.support.v7.widget.CardView>
The only change I've made from yours is, card_view:cardCornerRadius="8dp"> and removed the imageview(as no longer needed)
Screenshot of flashcard not filling to half of card:
I believe this is (almost) exact layout of what you want. It is pretty self-explanatory but feel free to ask if something's not clear.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:cardElevation="8dp"
card_view:cardCornerRadius="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout <!-- This is the specific part you asked to color -->
android:id="#+id/heading_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/teal_500"
android:padding="36dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="22 mins to Ancona"
android:textColor="#color/white"
android:textStyle="bold"
android:textSize="36sp" />
<TextView
android:id="#+id/tv_subheading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_below="#+id/tv_heading"
android:text="Light traffic on ss16"
android:textColor="#color/teal_200"
android:textSize="24sp" />
</LinearLayout>
<ImageView
android:id="#+id/iv_map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="Assigned delivery boy"
android:scaleType="fitXY"
android:src="#drawable/bg_map" />
<TextView
android:id="#+id/tv_footer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_below="#+id/tv_heading"
android:text="It is just an example!"
android:textColor="#color/grey_500"
android:textStyle="bold"
android:textSize="24sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
I have replaced your mapFragment (presumably) with imageView to reduce complications.
Update: As the question now addresses the infamous "round corner" problem, this is actually by design. Yes, it is a big flaw. But the solution (as given in docs Here) would be to use card_view:cardPreventCornerOverlap="false" attribute (which I don't think does anything good because it just makes card square again).
See these questions for a good reference to this problem:
Appcompat CardView and Picasso no rounded Corners
Make ImageView fit width of CardView
From my understanding, you can change the colour of a CardView in it's entirety but not parts of it. I'm not sure how that would even work.
What you can do, is nest a TextView with the title within the CardView, then colour the background of the TextView to the colour you would like. Use appropriate margins/padding for a uniform look. Add a background to your TextView and see what you get.
Your TextView is already using the match_parent parameter on your android:layout_width="" so you would only need to add the background like so:
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"
android:background="#FF4444"/>
To change the entire CardView colour like I mentioned at the beginning you can do it the same way or programmatically like so:
cardView.setCardBackgroundColor(COLOURHERE);
I'm using eclipse to code my android app and I'm wondering how I can change the background image of my MainActivity when I click a button. I have img1.png and img2.png. The background is currently set on img1.png with the following xml code:
<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:background="#drawable/img1"
tools:context=".MainActivity" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="46dp"
android:layout_marginTop="55dp"
android:background="#android:color/transparent"
android:text="" />
</RelativeLayout>
I'm just unsure what java code I would use to change the background image on btn1 click.
This code can be used to set background image programmattically
RelativeLayout layout =(RelativeLayout)findViewById(R.id.relativelayout);
layout.setBackgroundResource(R.drawable.img1);
This could be a solution.
In your layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lyt_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/img1"
tools:context=".MainActivity" >
In your Activity
RelativeLayout layout;
public void onCreate(Bundle savedInstanceState){
super.onCreate(Bundle savedInstanceState);
setContentView(your_xml.xml);
layout = (RelativeLayout) findById(R.id.lyt_main);
button = (Button) findById(R.id.lyt_main);
button.setOnClickListener(new OnClickListener{
public void onClick(View v) {
layout.setBackgroundDrawable(your_image));
}
});
}
Add android ID to Your Layout:
<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:background="#drawable/img1"
android:id="#+id/rlayout"
tools:context=".MainActivity" >
...
</RelativeLayout>
Now In Your MainActivity.java :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout rlayot = (RelativeLayout) findViewById(R.id.rlayout);
rlayot.setBackgroundResource(R.drawable.img2);
}
});
}