This question already has answers here:
AndroidStudio Cannot Find Layout
(2 answers)
Closed 2 years ago.
I am using Android Studio. I am currently trying to make a custom adapter and I have been having trouble with my .xml files. Although I have created them and added the content I would like to see in them, when I call for them in the main activity Java file, I get an error saying it does not exist. Additionally, the SetOnItemClickListener and setAdapter will not work. None of my other files show any sort of errors.
.xml I would like to show, titled characteritem_layout:
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detail_name"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detail_status"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detail_explanation"/>
</LinearLayout>
My code for the main activity:
package com.example.app.activities;
import ...
public class MainActivity extends AppCompatActivity {
private Button denButton;
private Button sweButton;
private Button aboutButton;
private TextView welcome;
private ArrayList<CharacterItem> characters;
private ListView charList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.characteritem_layout)
welcome = findViewById(R.id.welcome_screen);
//The other buttons work perfectly well.
initializeList();
final CharacterAdapter charAdapter = new CharacterAdapter(this, R.layout.characteritem_layout, characters);
characters.setAdapter(charAdapter);
characters.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), CharacterActivity.class);
intent.putExtra("charItem", characters.get(position));
startActivity(intent);
}
});
private void initializeList(){
characters = new ArrayList<CharacterItem>();
characters.add(new CharacterItem("Finland", false, "Not in progress yet"));
characters.add(new CharacterItem("Norway", true, "Getting the Viking trio in first!"));
characters.add(new CharacterItem("Iceland",false,"He's next!"));
}
}
first of all, to use setContentView twice will not be working in way you want
in my case, right click layout folder and then chose new Layout Resource file works
Related
I am developing a small project of test, and I wrote the following code.
I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button.
Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
Can anyone know how to fix this error, please?
public class Register2 extends AppCompatActivity {
Button mRegisterBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
mRegisterBtn = findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
}
});
}
}```
<?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"
android:background="#007FFF"
tools:context=".Register">
<Button
android:id="#+id/registerBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:text="Register"
android:textColor="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try using the Activity itself as the Context.
If you want a log, then make one
If you want the gray to go away, use a lambda
Log.d("REGISTER", "Setting listener");
mRegisterBtn.setOnClickListener(view -> {
Log.d("REGISTER", "Clicked!");
Toast.makeText(Register2.this, "Testing", Toast.LENGTH_LONG).show();
});
I noticed the SwipeRefreshLayout works when my RecyclerView is filled with data but not when the RecyclerView is empty. Is there a way to override this behavior?
My app fetches some data from the server and populates the RecyclerView. So for example, if the user has forgotten to turn on their internet but started my app, I want them to be able to turn it on and swipe up to refresh instead of going back and starting the activity again.
Here's is my activity's xml. I have removed some code to make this less verbose. I had one more button outside of the SwipeRefreshLayout and I have also removed my constraints.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".BreakfastActivity"
android:orientation="vertical">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/b_swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="0dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_breakfast"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
And this is the .java file:
public class BreakfastActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
// to display the menu
RecyclerView rv_breakfast;
RecyclerView.Adapter my_adapter;
// the actual menu
ArrayList<Menu> menu;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breakfast);
rv_breakfast = findViewById(R.id.rv_breakfast);
swipeRefreshLayout = findViewById(R.id.b_swipe_refresh_layout);
swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.setOnRefreshListener(this);
rv_breakfast.setLayoutManager(new LinearLayoutManager(this));
new GetMenu(this).execute();
}
#Override
public void onRefresh() {
new GetMenu(this).execute();
}
static class GetMenu extends GetMenuBase {
WeakReference<BreakfastActivity> context;
GetMenu(BreakfastActivity b) {
context = new WeakReference<>(b);
meal_type = "breakfast";
b.swipeRefreshLayout.setRefreshing(true);
}
#Override
protected void onPostExecute(JSONObject parent) {
// process the output of the server side script script
b.swipeRefreshLayout.setRefreshing(false);
}
}
The java file is again devoid of some code not concerning the question. GetMenuBase extends an AsyncTask and implements doInBackground() and makes a call to the server and returns the JSON output.
The problem is that when your RecyclerView is empty then your height will be 0dp because you've set the height to wrap_content and 0dp to your SwipeRefreshLayout.
Change the height of your SwipeRefreshLayout or your RecyclerView to match_parent.
I am trying to make a little app to try out some things for a bigger app I am developing. I want to add a viewpager that displays four images, I developed this viewpager alone and it worked, but when I tried to add it to my other app (with just a couple of buttons) with the tag, it does not show anything and I am really stuck in here. Is possible to add the Viewpager this way? Honestly I don't have that much experience in Java, I usually program only C and Assembler and I will be reaaally glad if you could help me.
This is the xml file with the button and the include:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculo Rapido"
android:id="#+id/btcr"
android:layout_gravity="center_vertical"
android:layout_weight="0.16"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculo Avanzado"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_below="#+id/btcr" />
<include layout="#layout/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:translationZ="15dp" />
Now, the MainActivity, which holds the button activity because I kept the Viewpager inside an Activity that's linked with the viewpager original layout
Button siguiente;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
siguiente = (Button)findViewById(R.id.btcr);
siguiente.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent siguiente = new Intent(MainActivity.this, Main2Activity.class);
startActivity(siguiente);
}
});
}
And lastly, the code for the mainpager main activity, this uses a CustomPagerAdapter saved in another java class. As I told before, this viewpager does work alone, but when I try to implement it here, with the /include tag, it doesn't show anything.
public class MainActivity extends Activity {
CustomPagerAdapter mCustomPagerAdapter;
ViewPager mViewPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
Button siguiente;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// == Setting up the ViewPager ==
mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mViewPager.setCurrentItem(currentPage++);
if (currentPage == 5) {
currentPage = 0;
mViewPager.setCurrentItem(currentPage++, false);
}
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 2000, 2000);
}
Sorry if it is too long guys, but I am a little frustrated, I have tried a lot of things but it isn't working yet. Either the buttons do their thing and the ViewPager doesn't work or the ViewPager works but the buttons are dead.
I will reaaally aprecciate your help :)
create a new xml file inside layout folder and name it secondactivity.xml
and put this code
<?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.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager">
</android.support.v4.view.ViewPager>
</LinearLayout>
Now inside your Main2Activity.class
change
setContentView(R.layout.activity_main);
to
setContentView(R.layout.secondactivity);
And remove the include from your previous xml
Turns out, what I needed was just the simple solution. I had to put the viewpager on my activity's layout file as another object, just configuring its size and position. And then, on my onCreate I pasted the code of my functioning ViewPager. Quite simple, without requiring another layouts :)
I'm currently attempting to implement swipe-to-refresh layout into relative layout, but it is extremely insensitive and unstable. When I pull down the screen, it usually either doesn't refresh or it refreshes without progress bar.
<android.support.v4.widget.SwipeRefreshLayout
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: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.miaor.tutorialweather.MainActivity"
android:id="#+id/refreshLayout"
android:background="#fe970b">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
public class MainActivity extends AppCompatActivity{
public static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.TimeString) TextView mTimeLabel;
#BindView(R.id.TemperatureLabel) TextView mTemperatureLabel;
#BindView(R.id.HumidityValue) TextView mHumidityValue;
#BindView(R.id.rainingChanceValue) TextView mChance;
#BindView(R.id.weatherIcon) ImageView mWeatherIcon;
#BindView(R.id.SummaryText) TextView mSummaryText;
#BindView(R.id.refreshLayout) SwipeRefreshLayout mSwipeRefreshLayout;
///why do we make a new variable of CurrentWeather
private CurrentWeather mCurrentWeather;
private String apiKey = "6b9448b8e21c2abe2fb623b25554a77c";
private double latitude = 31.230708;
private double longitude = 121.472916;
private String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
///implement swipe-to-refresh feature
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(TAG, "onRefresh is working");
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
You can't implement SwipeToRefreshLayout with RelativeLayout as its child. You need to have a scrollable view as its only child. e.g. Listview, RecyclerView, ScrollView. That is the reason why it is not working as expected for you.
That is not the right position.
You need type like this:
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/your_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
YOUR RELATIVE LAYOUT HERE
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
Your code looks fine, it's weird that it's not working correctly... Maybe it's because of the ButterKnife library? I don't think that's the problem, but it will be worth the shot to get views manually to see if that's the problem
Then, if you need the loading animation to appear/hide you can use mSwipeRefreshLayout.setRefreshing(boolean);
For example in my app I attach the listener first (as you did in your example) and then I use the following code to show the loading animation while I fetch the data.
// Show loading while fetching the first set of data
mainSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mainSwipeRefreshLayout.setRefreshing(true);
}
});
In my fetchData() method I use the following line to hide the animation again when it finishes fetching the data.
// On load complete stop refresh animation
mainSwipeRefreshLayout.setRefreshing(false);
Hope this helps!
Andres.
This question already has answers here:
Your content must have a ListView whose id attribute is 'android.R.id.list'
(7 answers)
Closed 7 years ago.
I have written code about ListView in Android with Eclipse. I have followed tutorial based on book. But after i copied the code and run with Emulator. The Force Close message appeared. Like the image below:
I don't know whats the probem occured. Instead, i have searched the solution in this question:
Can't create android onListItemClick method
And my code like the image below:
The image below shown the logcat:
Can you give me solutions?
Make sure your ListView is named <ListView android:id="#android:id/list".
Since you are using a ListActivity (the same goes for ListFragments), this is the only possible name for your ListView.
try this,
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" >
<TextView
android:id="#+id/output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#758AA7"
android:padding="1px"
android:text="Click : "
android:textColor="#ffffff" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends ListActivity {
TextView content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
content = (TextView) findViewById(R.id.output);
String[] CoffeeShop = {"Creation","Starbucks","Caribou","Mo'Joe" };
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, CoffeeShop);
// Assign adapter to List
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) l.getItemAtPosition(position);
content.setText("Click : \n Position :" + itemPosition
+ " \n ListItem : " + itemValue);
}
}